﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Marbles.Core.Connectors;
using System.Data;

namespace Marbles.Core.Content.Pages
{
    public class PageDefinition
    {
        public string this[string key]
        {
            get
            {
                foreach (string s in _content.Keys) { if (s.ToLower() == key.ToLower()) { return _content[s]; } }
                return string.Empty;
            }
            set
            {
                bool fnd = false;
                if (string.IsNullOrEmpty(key)) { return; }
                foreach (string s in _content.Keys) { if (s.ToLower() == key.ToLower()) { _content[s] = value; fnd = true; break; } }
                if (!fnd) { _content.Add(key.ToLower(), value); }
            }
        }

        public bool AllowComments { get { return _allowcomments; } set { _allowcomments = value; } }
        public string LastAccessDate { get { return _LastAccess.Year > 1980 ? _LastAccess.ToString("dd/MM/yyyy HH:mm:ss") : ""; } }
        public DateTime LastAccess { get { return _LastAccess; } }
        public string SiteName { get { return _sitename; } }
        public string Description { get { return _Description.Trim(); } set { _Description = value.Trim(); } }
        public string Keywords { get { return _Keywords.Trim(); } set { _Keywords = value.Trim(); } }
        public string PageName { get { return _pagename; } set { _pagename = value; } }
        public string Title { get { return _title.Trim(); } set { _title = value.Trim(); } }
        public Dictionary<string, string> Content { get { return _content; } set { _content = value; } }
        public string Link { get { return HttpContext.Current.Request.Url.ToString(); } }
        public string ManagingEditor { get { return _editor; } set { _editor = value; } }
        public DateTime PublishDate { get { return _pubdate; } set { _pubdate = value; } }
        public DateTime CreationDate { get { return _creationdate; } }
        public bool Published { get { return _published; } set { _published = value; } }
        public string SiteId { get { return _siteid; } }
        public string ParentPageName { get { return _parentpageid; } set { _parentpageid = value; } }
        public bool Syndicate { get { return _syndicate; } set { _syndicate = value; } }
        public bool AllowFeedDiscovery { get { return _allowfeeddiscovery; } set { _allowfeeddiscovery = value; } }
        public bool ApplyTheme { get { return _ApplyTheme; } set { _ApplyTheme = value; } }
        public bool Found { get { return _found; } }
        public string TemplateName { get { return _templatename; } set { _templatename = value; } }

        private bool _found = false;
        private bool _ApplyTheme = false;
        private bool _allowfeeddiscovery = false;
        private bool _syndicate = false;
        private string _editor = string.Empty;
        private string _Description = string.Empty;
        private string _Keywords = string.Empty;
        private DateTime _pubdate = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
        private DateTime _creationdate = DateTime.Now;
        private bool _published = false;
        private string _sitename = string.Empty;
        private string _pagename = string.Empty;
        private string _title = string.Empty;
        private Dictionary<string, string> _content = null;
        private string _siteid = string.Empty;
        private string _parentpageid = string.Empty;
        private string _templatename = string.Empty;
        private DateTime _LastAccess = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
        private bool _allowcomments = false;

        public PageDefinition()
        {
            _found = false;
            _allowfeeddiscovery = false;
            _syndicate = false;
            _editor = string.Empty;
            _Description = string.Empty;
            _Keywords = string.Empty;
            _pubdate = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
            _creationdate = DateTime.Now;
            _published = false;
            _sitename = string.Empty;
            _pagename = string.Empty;
            _title = string.Empty;
            _content = new Dictionary<string, string>();
            _siteid = string.Empty;
            _parentpageid = string.Empty;
            _templatename = string.Empty;
            _ApplyTheme = true;
            _LastAccess = Marbles.Core.Connectors.DataConnection.MinimumDateTime;
            _allowcomments = false;
        }

        public PageDefinition(string SiteName, string PageName)
            : this()
        {
            Load(SiteName, PageName);
        }

        internal PageDefinition(DataRow row)
        {
            _found = true;
            _ApplyTheme = Convert.ToBoolean(row["applytheme"]);
            _templatename = row["templatename"].ToString();
            _parentpageid = row["parentpagename"].ToString();
            _allowfeeddiscovery = Convert.ToBoolean(row["allowfeeddiscovery"]);
            _Description = row["description"].ToString();
            _Keywords = row["keywords"].ToString();
            _siteid = row["siteid"].ToString();
            _title = row["title"].ToString();
            _editor = row["managingEditor"].ToString();
            _pubdate = Convert.ToDateTime(row["publishDate"].ToString());
            _syndicate = Convert.ToBoolean(row["syndicate"]);
            _pagename = row["pagename"].ToString();
            _LastAccess = Convert.ToDateTime(row["lastaccess"]);
            _allowcomments = Convert.ToBoolean(row["allowcomments"]);
            _creationdate = Convert.ToDateTime(row["creationdate"]);
            _published = Convert.ToBoolean(row["published"]);
        }

        public void Load(string SiteName, string PageName)
        {
            _sitename = SiteName;
            _editor = string.Empty;
            _pubdate = DateTime.Now;
            _found = false;
            _pagename = PageName;
            _title = string.Empty;
            _content.Clear();
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT a.templatename, a.applytheme, a.allowcomments, a.parentpagename, a.creationdate, a.published, a.lastaccess, a.allowfeeddiscovery, a.syndicate, a.Description, a.keywords, a.siteid, a.title, a.managingEditor, a.publishDate, b.name, b.content FROM pages a LEFT JOIN content b ON a.siteid = b.siteid AND a.pagename = b.pagename INNER JOIN sites c ON a.siteid = c.siteid WHERE c.sitename = @sitename AND a.pagename = @pagename");
            cmd.AddParameter("@sitename", _sitename);
            cmd.AddParameter("@pagename", _pagename);
            DataTable dt = dbc.FetchDataTable(cmd);

            if (dt.Rows.Count > 0)
            {
                _found = true;
                _ApplyTheme = Convert.ToBoolean(dt.Rows[0]["applytheme"]);
                _creationdate = Convert.ToDateTime(dt.Rows[0]["creationdate"]);
                _published = Convert.ToBoolean(dt.Rows[0]["published"]);
                _allowcomments = Convert.ToBoolean(dt.Rows[0]["allowcomments"]);
                _LastAccess = Convert.ToDateTime(dt.Rows[0]["lastaccess"]);
                _parentpageid = dt.Rows[0]["parentpagename"].ToString();
                _allowfeeddiscovery = Convert.ToBoolean(dt.Rows[0]["allowfeeddiscovery"]);
                _Description = dt.Rows[0]["description"].ToString();
                _Keywords = dt.Rows[0]["keywords"].ToString();
                _siteid = dt.Rows[0]["siteid"].ToString();
                _templatename = dt.Rows[0]["templatename"].ToString();
                _title = dt.Rows[0]["title"].ToString();
                _editor = dt.Rows[0]["managingEditor"].ToString();
                _pubdate = Convert.ToDateTime(dt.Rows[0]["publishDate"].ToString());
                _syndicate = Convert.ToBoolean(dt.Rows[0]["syndicate"]);

                foreach (DataRow dr in dt.Rows)
                {
                    _content.Add(dr["name"].ToString().ToLower(), dr["content"].ToString());
                }
            }
        }

        public static PageDefinition CreateNew(string SiteName)
        {
            PageDefinition def = new PageDefinition();
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT siteid FROM sites WHERE sitename = @sitename");
            cmd.AddParameter("@sitename", SiteName);
            DataTable dt = dbc.FetchDataTable(cmd);

            if (dt.Rows.Count > 0)
            {
                def._sitename = SiteName;
                def._siteid = dt.Rows[0]["siteid"].ToString();
            }

            return def;
        }

        public void Insert(string updateby)
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("INSERT INTO pages (applytheme, templatename, allowcomments,lastaccess,siteid, pagename, title, managingeditor, publishdate, keywords, description, syndicate, allowfeeddiscovery, parentpagename, published, creationdate) VALUES (@applytheme, @templatename, @allowcomments,@lastaccess,@siteid, @pagename, @title, @managingeditor, @publishdate, @keywords, @description, @syndicate, @allowfeeddiscovery, @parentpagename, @published, @creationdate);");
            cmd.AddParameter("@applytheme", _ApplyTheme);
            cmd.AddParameter("@published", _published);
            cmd.AddParameter("@creationdate", _creationdate);
            cmd.AddParameter("@templatename", _templatename);
            cmd.AddParameter("@lastaccess", new DateTime(1980, 1, 1, 0, 0, 0));
            cmd.AddParameter("@siteid", _siteid);
            cmd.AddParameter("@parentpagename", _parentpageid);
            cmd.AddParameter("@syndicate", _syndicate);
            cmd.AddParameter("@allowfeeddiscovery", _allowfeeddiscovery);
            cmd.AddParameter("@pagename", _pagename);
            cmd.AddParameter("@allowcomments", _allowcomments);
            cmd.AddParameter("@title", _title);
            cmd.AddParameter("@managingeditor", _editor);
            cmd.AddParameter("@publishdate", _pubdate);
            cmd.AddParameter("@keywords", _Keywords);
            cmd.AddParameter("@description", _Description);

            DataTable dt = dbc.FetchDataTable(cmd);
            PageDefinition tmp = new PageDefinition(this.SiteName, this.PageName);

            foreach (string key in _content.Keys)
            {
                if (string.IsNullOrEmpty(key)) { continue; }
                cmd = new Command("INSERT INTO content(siteid, pagename, name, content, updatedate, updateby) VALUES (@siteid, @pagename, @name, @content, @updatedate, @updateby)");
                cmd.AddParameter("@siteid", _siteid);
                cmd.AddParameter("@pagename", _pagename);
                cmd.AddParameter("@name", key);
                cmd.AddParameter("@content", _content[key]);
                cmd.AddParameter("@updatedate", DateTime.Now);
                cmd.AddParameter("@updateby", updateby);
                dbc.ExecuteCommand(cmd);
            }

        }

        public void Publish()
        {
            _published = true;
            _pubdate = DateTime.Now;
        }

        public void Update(string updateby)
        {

            DataConnection dbc = new DataConnection();
            Command cmd = new Command("UPDATE pages SET applytheme = @applytheme, published = @published, creationdate = @creationdate, templatename = @templatename, allowcomments = @allowcomments, parentpagename = @parentpagename, allowfeeddiscovery = @allowfeeddiscovery, syndicate = @syndicate, keywords = @keywords, description = @description, title = @title, managingeditor = @managingeditor, publishdate = @publishdate WHERE siteid = @siteid AND pagename = @pagename");
            cmd.AddParameter("@published", _published);
            cmd.AddParameter("@applytheme", _ApplyTheme);
            cmd.AddParameter("@creationdate", _creationdate);
            cmd.AddParameter("@syndicate", _syndicate);
            cmd.AddParameter("@siteid", _siteid);
            cmd.AddParameter("@templatename", _templatename);
            cmd.AddParameter("@parentpagename", _parentpageid);
            cmd.AddParameter("@pagename", _pagename);
            cmd.AddParameter("@title", _title);
            cmd.AddParameter("@managingeditor", _editor);
            cmd.AddParameter("@allowcomments", _allowcomments);
            cmd.AddParameter("@publishdate", _pubdate);
            cmd.AddParameter("@keywords", _Keywords);
            cmd.AddParameter("@description", _Description);
            cmd.AddParameter("@allowfeeddiscovery", _allowfeeddiscovery);

            dbc.ExecuteCommand(cmd);
            cmd = new Command("DELETE FROM content WHERE siteid = @siteid AND pagename = @pagename");
            cmd.AddParameter("@siteid", _siteid);
            cmd.AddParameter("@pagename", _pagename);
            dbc.ExecuteCommand(cmd);

            foreach (string key in _content.Keys)
            {
                if (string.IsNullOrEmpty(key)) { continue; }
                cmd = new Command("INSERT INTO content(siteid, pagename, name, content, updatedate, updateby) VALUES (@siteid, @pagename, @name, @content, @updatedate, @updateby)");
                cmd.AddParameter("@siteid", _siteid);
                cmd.AddParameter("@pagename", _pagename);
                cmd.AddParameter("@name", key);
                cmd.AddParameter("@content", _content[key]);
                cmd.AddParameter("@updatedate", DateTime.Now);
                cmd.AddParameter("@updateby", updateby);
                dbc.ExecuteCommand(cmd);
            }
        }

        public void UpdateLastAccess()
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("UPDATE pages SET lastaccess = @lastaccess WHERE siteid = @siteid AND pagename = @pagename");
            cmd.AddParameter("@lastaccess", DateTime.Now);
            cmd.AddParameter("@siteid", _siteid);
            cmd.AddParameter("@pagename", _pagename);
            dbc.ExecuteCommand(cmd);
        }

    }
}
